package com.sczmgk.track.activity.trackactivity;

import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiBoundSearchOption;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.sczmgk.track.R;
import com.sczmgk.track.base.CheckPermissionBaseActivity;
import com.sczmgk.track.db.impl.UserDaoImpl;
import com.sczmgk.track.entity.User;
import com.sczmgk.track.utils.MapUtil;
import com.sczmgk.track.utils.MyLog;
import com.sczmgk.track.utils.MyToast;
import com.sczmgk.track.utils.Tools;

import java.util.ArrayList;
import java.util.List;

import static com.sczmgk.track.MyApp.currPoi;
import static com.sczmgk.track.entity.CurrentLocation.latitude;
import static com.sczmgk.track.entity.CurrentLocation.longitude;

/**
 * Created by Administrator on 2017/9/27.
 * 检索
 */
public class TracingSearchActivity extends CheckPermissionBaseActivity {

    private int currselect;
    private final int RADUIS = 500;
    private static final int REFRESH_UI = 123;
    public PoiSearch mPoiSearch;
    private List<PoiInfo> allPoiInfos;
    private MySearchAdapter searchAdapter;
    private PoiInfo poiInfoSelect;
    private EditText mEtSearchAddr;
    private Button mBtnSearch;
    private MapUtil mapUtil;
    private ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_search);
        setTitle(R.string.adjust_title);
        setRightBtnTextColor(R.color.button_text_color);
        setRightBtnVisibility(View.VISIBLE);
        setRightBtnText(R.string.sure);
        setRightBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_OK);
                currPoi = poiInfoSelect;
                finish();
            }
        });
        mapUtil = new MapUtil();
        mapUtil.init((MapView) findViewById(R.id.tracing_mapView));
        User user  = UserDaoImpl.getLoginUser(TracingSearchActivity.this);
        String imagePath = "";
        if(user != null){
            imagePath = user.imageLocalPath;
        }
        mapUtil.addMyMarker(new LatLng(latitude, longitude), TracingSearchActivity.this, imagePath);
        mapUtil.animateMapStatus(new LatLng(latitude, longitude), 15.0f);
        isShowLeftView(false);

        initTrack();

        initData();

        setSearchListener();

    }

    private void initTrack() {
        //搜索框的容器
        findViewById(R.id.ll_tracing_search_container).setVisibility(View.VISIBLE);
        mEtSearchAddr = (EditText) findViewById(R.id.et_tracing_input_address);
        mBtnSearch = (Button) findViewById(R.id.btn_tracint_search);

        //搜索的内容
        mListView = (ListView) findViewById(R.id.lv_tracing_search_list);
        mListView.setVisibility(View.VISIBLE);
    }

    private void initData() {

        //初始化
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(poiListener);

        allPoiInfos = new ArrayList<>();

        searchAdapter = new MySearchAdapter();
        mListView.setAdapter(searchAdapter);

        mapUtil.getAddress(new LatLng(latitude, longitude), new MapUtil.OnGetGeoCallback() {
            @Override
            public void onSuccess(String address) {

            }

            @Override
            public void onFail() {

            }

            @Override
            public void onSuccess(PoiInfo poi) {
                MyLog.d(TAG, "进入签到界面,根据坐标取位置信息: " + poi.address);

            }

            @Override
            public void onSuccess(List<PoiInfo> poiinfs) {
                allPoiInfos = poiinfs;
                poiInfoSelect = poiinfs.get(currselect);
                searchAdapter.notifyDataSetChanged();
            }
        });
    }

    OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener() {

        public void onGetPoiResult(PoiResult result) {

            //获取POI检索结果
            if (result.error != SearchResult.ERRORNO.NO_ERROR) {
                //详情检索失败
                MyLog.e(TAG, result.error.toString());
                MyToast.show(TracingSearchActivity.this, "未找到结果");
            } else {
                if (allPoiInfos.size() > 0) {
                    allPoiInfos.clear();
                }
                //检索成功
                for (PoiInfo poiInfo : result.getAllPoi()) {
                    //uid是POI检索中获取的POI ID信息
//                    mPoiSearch.searchPoiDetail((new PoiDetailSearchOption()).poiUid(poiInfo.uid));
                    MyLog.d(TAG, "城市 : " + poiInfo.city + "--- 名字 : " + poiInfo.name + "--- 地址 : " + poiInfo.address);
                    if (poiInfo.location != null) {
                        MyLog.w(TAG, "distance: " + mapUtil.getDistance(new LatLng(latitude, longitude), poiInfo.location));
                        if (mapUtil.getDistance(new LatLng(latitude, longitude), poiInfo.location) < RADUIS) {

                            allPoiInfos.add(poiInfo);
                        }
                    }
                }
                mHandler.sendEmptyMessage(REFRESH_UI);
            }
        }

        public void onGetPoiDetailResult(PoiDetailResult result) {
            //获取Place详情页检索结果
        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

        }
    };

    private void setSearchListener() {


        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                poiInfoSelect = null;
                poiInfoSelect = allPoiInfos.get(i);
                currselect = i;
                User loginUser = UserDaoImpl.getLoginUser(TracingSearchActivity.this);
                String imagePath="";
                if(loginUser != null){
                    imagePath = loginUser.imageLocalPath;

                }
                mapUtil.addMyMarker(poiInfoSelect.location, TracingSearchActivity.this, imagePath);
//                mapUtil.baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(poiInfoSelect.location));
                mapUtil.animateMapStatus(poiInfoSelect.location, 15.0f);

                searchAdapter.notifyDataSetChanged();
            }
        });

        mBtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String inputAddress = mEtSearchAddr.getText().toString().trim();
                if (Tools.isEmpty(inputAddress)) {
                    MyToast.show(TracingSearchActivity.this, "请输入搜索内容");
                    return;
                }
                nearbySearch(inputAddress, 0);
            }
        });
    }

    @Override
    public void onSelectedPhonePermission(String phoneNumber) {

    }

    @Override
    public void onSelectedStroage(int position) {

    }

    @Override
    public void onSelectCamera(int position) {

    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }

    private class MySearchAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return allPoiInfos.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {

            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(TracingSearchActivity.this, R.layout.item_tracing_search, null);
                holder = new ViewHolder();
                holder.tvAddress = (TextView) convertView.findViewById(R.id.tv_item_tracing_search_address);
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_item_tracing_search_name);
                holder.mSelectIv = (ImageView) convertView.findViewById(R.id.iv_select_address);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            PoiInfo poiInfo = allPoiInfos.get(i);
            holder.mSelectIv.setVisibility(View.INVISIBLE);
            holder.tvName.setText(poiInfo.name);
            holder.tvAddress.setText(poiInfo.address);

            //设置选中后的按钮
            if(i == currselect){
                holder.mSelectIv.setVisibility(View.VISIBLE);
            }
            return convertView;
        }
    }

    private class ViewHolder {
        TextView tvAddress;
        TextView tvName;
        ImageView mSelectIv;
    }

    @Override
    public void handleMessage(Message msg) {

        switch (msg.what) {
            case REFRESH_UI:
                searchAdapter.notifyDataSetChanged();
                break;
        }
    }

    /**
     * 附近检索
     */
    public void nearbySearch(String keyword, int page) {
        PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption();
        nearbySearchOption.location(new LatLng(latitude, longitude));
        nearbySearchOption.keyword(keyword);
        nearbySearchOption.radius(RADUIS);// 检索半径，单位是米
        nearbySearchOption.pageNum(page);
        nearbySearchOption.sortType(PoiSortType.distance_from_near_to_far);
        mPoiSearch.searchNearby(nearbySearchOption);// 发起附近检索请求
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapUtil.clear();
        if (mPoiSearch != null) {
            mPoiSearch.destroy();
        }
    }

    /**
     * 城市内搜索
     */
    private void citySearch(int page, String keyword) {
        // 设置检索参数
        PoiCitySearchOption citySearchOption = new PoiCitySearchOption();
        citySearchOption.city("成都");// 城市
        citySearchOption.keyword(keyword);// 关键字
        citySearchOption.pageCapacity(15);// 默认每页10条
        citySearchOption.pageNum(page);// 分页编号
        // 发起检索请求
        mPoiSearch.searchInCity(citySearchOption);
    }

    /**
     * 范围检索
     */
    private void boundSearch(String keyword, int page) {

        PoiBoundSearchOption boundSearchOption = new PoiBoundSearchOption();
        LatLng southwest = new LatLng(latitude - 0.01, longitude - 0.012);// 西南
        LatLng northeast = new LatLng(latitude + 0.01, longitude + 0.012);// 东北
        // 得到一个地理范围对象
        LatLngBounds bounds = new LatLngBounds.Builder().include(southwest).include(northeast).build();
        boundSearchOption.bound(bounds);// 设置poi检索范围
        boundSearchOption.keyword(keyword);// 检索关键字
        boundSearchOption.pageNum(page);
        mPoiSearch.searchInBound(boundSearchOption);// 发起poi范围检索请求
    }
    @Override
    protected void onPause() {
        super.onPause();
        mapUtil.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapUtil.onResume();
    }
}
